package com.xncoding.jwt.api;


import cn.hutool.core.thread.ThreadUtil;
import com.xncoding.jwt.config.web.swagger.SwaggerTagConst;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Slf4j
@Api(value = "123", tags = SwaggerTagConst.SYSTEM.threadpool, description = "1123")
@RestController
@RequestMapping("threadpool")
public class ThreadPoolController {
    @Resource private ThreadPoolTaskExecutor asyncServiceExecutor;

    @ApiOperation("提交到线程池")
    @GetMapping
    public List<String> list(@RequestParam(required = false, defaultValue = "10") int size){
        if(size <= 0){
            size = 10;
        }
        List<Future<String>> futureList=new ArrayList<>(size);
        CountDownLatch downLatch = new CountDownLatch(size);
        for (int i = 0; i < size; i++) {
            futureList.add(asyncServiceExecutor.submit(new DealJob(i, downLatch)));
        }
        try {
            Thread.yield();
            downLatch.await();
        }catch (Exception e){
            log.error("------------->",e);
        }
        List<String> list = new ArrayList<>(size);
        for (Future<String> future : futureList) {
            try {
                list.add(future.get());
            }catch (Exception e){
                log.error("------------->",e);
            }
        }
        return list;
    }

}
class DealJob implements Callable<String>{
    private int no;
    private CountDownLatch downLatch;
    public DealJob(int no, CountDownLatch downLatch){
        this.no = no;
        this.downLatch =downLatch;
    }
    @Override
    public String call() {
        // todo 模拟 执行操作
        ThreadUtil.sleep(2_000L);
        downLatch.countDown();
        return no+"---->"+no;
    }
}